<?php namespace App\Core\Repository\Criterias\Filters;

use App\Core\Repository\Criteria;
use App\Core\Repository\Repository;
use Input;

class InputTimeRangeCriteria extends Criteria{
    
    protected $field;
    protected $begin;
    protected $end;
    protected $edge;
    
    public function __construct($field = 'created_at', $begin = 'begin_time', $end = 'end_time', $edge = 'both') {
        $this->field = $field;
        $this->begin = Input::get($begin, '');
        $this->end = Input::get($end, '');
        $this->edge = $edge;
        $this->setName('filter_time_range_'.$this->field);
    }

    public function apply(Repository $repository){
        parent::apply($repository);
        $field = $this->formatField($this->model, $this->field);
        if($this->begin){
            $this->query->where($field, (in_array($this->edge, ['both', 'begin']) ? '>=' : '>'), strtotime($this->begin));
        }
        if($this->end){
            $this->query->where($field, (in_array($this->edge, ['both', 'end']) ? '<=' : '<'), strtotime($this->end)+3600*24);
        }
    }
}